package moxl.tokenizer.xml.doctype;

import java.io.IOException;

import moxl.reader.LocateableReader;
import moxl.tokenizer.AbstractTokenizerState;
import moxl.tokenizer.EndOfFileState;
import moxl.tokenizer.Token;
import moxl.tokenizer.TokenReadyState;
import moxl.tokenizer.TokenizerStateMachine;
import moxl.tokenizer.xml.XmlTokenType;
import moxl.tokenizer.xml.document.DocumentStartState;

public class DocumentTypeBodyStartState extends AbstractTokenizerState
{
	private static AbstractTokenizerState instance = new DocumentTypeBodyStartState();

	public static AbstractTokenizerState getInstance()
	{
		return instance;
	}

	@Override
	public boolean isStartState()
	{
	    return true;
	}
	
	@Override
	public void accept(TokenizerStateMachine stateMachine, Token token, LocateableReader reader) throws IOException
	{
		reader.mark(1);
		token.setTokenType(XmlTokenType.DOCTYPE_BODY);
		int c = reader.read();
		if (c == -1)
		{
			stateMachine.changeState(EndOfFileState.getInstance());
		}
		else if (c == '<')
		{
			stateMachine.pushDelimiter((char) c);
			token.append(c);
		}
		else if (c == '>')
		{
			if (stateMachine.isDelimiterStackEmpty())
			{
				stateMachine.changeState(TokenReadyState.getInstance());
				reader.reset();
				stateMachine.setStartState(DocumentStartState.getInstance());
			}
			else
			{
				char openingDelimiter = stateMachine.pop();
				if (openingDelimiter != '<')
				{
					throw new IllegalStateException();
				}
			}
		}
		else
		{
			token.append(c);
		}
	}

}
